package simplescenegraph.assets;

import java.awt.image.BufferedImage;
import java.awt.image.PixelGrabber;
import java.io.IOException;
import java.nio.ByteBuffer;
import javax.imageio.ImageIO;
import com.sun.opengl.util.BufferUtil;

public class TextureLoader {
	
	public static Texture readTexture(String fileName) throws IOException {
		return readTexture(fileName, false);
	}
	
	public static Texture readTexture(String fileName, boolean hasAlpha) throws IOException {
		BufferedImage bufferedImage;
		
		if (fileName.endsWith(".bmp")) {
			bufferedImage = BitmapLoader.loadBitmap(fileName);
		} else {
			bufferedImage = readImage(fileName);
			hasAlpha = bufferedImage.getTransparency() == BufferedImage.TRANSLUCENT;
		}
		
		Texture texture = new Texture(fileName, bufferedImage.getWidth(), bufferedImage.getHeight(), hasAlpha);
		
		grabPixels(texture, bufferedImage);
		
		return texture;
	}
	
	private static BufferedImage readImage(String resourceName) throws IOException {
		return ImageIO.read(ResourceLoader.getResourceAsStream(resourceName));
	}
	
	private static void grabPixels(Texture texture, BufferedImage image) {
		int[] packedPixels = new int[image.getWidth() * image.getHeight()];
		
		PixelGrabber pixelgrabber = new PixelGrabber(image, 0, 0, image.getWidth(), image.getHeight(), packedPixels, 0, image.getWidth());
		try {
			pixelgrabber.grabPixels();
		} catch (InterruptedException e) {
			throw new RuntimeException();
		}
		
		int bytesPerPixel = texture.hasAlpha() ? 4 : 3;
		ByteBuffer unpackedPixels = BufferUtil.newByteBuffer(packedPixels.length * bytesPerPixel);
		
		for (int row = image.getHeight() - 1; row >= 0; row--) {
			for (int col = 0; col < image.getWidth(); col++) {
				int packedPixel = packedPixels[row * image.getWidth() + col];
				unpackedPixels.put((byte) ((packedPixel >> 16) & 0xFF));
				unpackedPixels.put((byte) ((packedPixel >> 8) & 0xFF));
				unpackedPixels.put((byte) ((packedPixel >> 0) & 0xFF));
				if (texture.hasAlpha()) {
					unpackedPixels.put((byte) ((packedPixel >> 24) & 0xFF));
				}
			}
		}
		
		unpackedPixels.flip();
		
		texture.setPixels(unpackedPixels);
	}
	
}